package com.lhys.interceptor;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.lhys.common.ApiResultMsg;
import com.lhys.common.ResultInfo;
import com.lhys.utils.JwtUtils;
import io.jsonwebtoken.Claims;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Created with IntelliJ IDEA.
 * User: xiaoqi
 * Date: 2021/5/12
 * Time: 下午 14:07
 * Description: 登录拦截器
 */
public class LoginInterceptor implements HandlerInterceptor {

    @Autowired
    private JwtUtils jwtUtils;

    @Value("${jwt.header}")
    private String header;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        if (request.getRequestURI().contains("login") || request.getRequestURI().contains("register")
                || request.getRequestURI().contains("upload") || request.getRequestURI().contains("static") || request.getRequestURI().contains("druid")) {
            return true;
        }
        request.setCharacterEncoding("utf-8");
        response.setCharacterEncoding("utf-8");
        response.setContentType("application/json;charset=utf-8");
        ObjectMapper objectMapper = new ObjectMapper();
        try {
            // 获取用户发送请求 传递过来的token信息
            String token = request.getHeader(this.header);

            // 如果token为null 用户没有登录
            if (token == null) {
                String resultMsg = objectMapper.writeValueAsString(ApiResultMsg.error(ResultInfo.NO_LOGIN));
                response.getWriter().write(resultMsg);
                return false;
            }
            Claims claims = jwtUtils.resolverToken(token);
            if (claims == null) {
                String resultMsg = objectMapper.writeValueAsString(ApiResultMsg.error(ResultInfo.TOKEN_ERROR));
                response.getWriter().write(resultMsg);
                return false;
            }
            System.out.println("发送请求的客户端名：" + claims.getSubject());
            return true;
        } catch (JsonProcessingException e) {
            e.printStackTrace();
            String resultMsg = objectMapper.writeValueAsString(ApiResultMsg.error(ResultInfo.SERVER_ERROR));
            response.getWriter().write(resultMsg);
            return false;
        }
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {

    }
}